// mobile bind
// ============

define(['zepto', 'utils'], function($, utils){
  return {
    init: function(data) {
      utils.configWeixin(data.jsConfig, false);
      this.bindSubmit();
    },

    /**
     * Bind mobile binding page event
     */
    bindSubmit: function() {
      var that = this,
          $name = $('input[name="name"]');
          $address = $('textarea[name="address"]');

      // On submiting mobile
      $(document).on('click', '#submit', function(e) {
        e.preventDefault()
        
        var submitingStatus = $(this).data("submiting");
        if(submitingStatus != "true") {
          $("#submit").data("submiting", "true");
          var address = $address.val().trim();
          var name = $name.val().trim();
          if(!name) return $.toast('请输入姓名')
          if(!address) return $.toast('请输入详细地址')
          
          var submiting = that.submitAddress(name, address)
          $.when(submiting).done(function(data) {
            $("#submit").data("submiting", "false");
            if(data.redirect && data.redirect != '/') {
              window.location.href = window.__CTX__.root + data.redirect;
            } else {
              window.location.href = window.__CTX__.root + "/profile";
            }
          })
        }
      })
    },

    submitAddress: function(name, address) {
      var that = this, defer = $.Deferred()
      $.showIndicator()
      $.post(window.__CTX__.root + '/profile/edit-address', { '_method': 'PATCH', 'name': name, 'address': address})
        .done(function(response) {
          $.hideIndicator()
          utils.processResult(response, function(result) {
            $.toast(result.message || '编辑地址成功')
            defer.resolve(result.data)
          }, function(result) {
            $("#submit").data("submiting", "false");
            $.toast(result.message || '编辑地址失败')
          })
        })
        
      return defer.promise()
    }
    
  }

})